<template>
	<div class="chat" style="height: 100vh;">
		<div :class="['TUI-chat', !isPC && 'TUI-chat-h5']" style="height: 100%;">
			<div v-if="!currentConversationID" :class="['TUI-chat-default', !isPC && 'TUI-chat-h5-default']">
				<slot></slot>
			</div>
			<div v-if="currentConversationID" :class="['TUI-chat', !isPC && 'TUI-chat-h5']"
				style="display: flex; flex-direction: column; height: 100%;">
				<!-- <ChatHeader :class="[ 'TUI-chat-header', !isPC && 'TUI-chat-H5-header', isUniFrameWork && 'TUI-chat-uniapp-header', ]" @closeChat="closeChat"></ChatHeader>
				<Forward></Forward> -->
				
				<view class="top">
					<view class="status-bar"></view>
					<view class="title-bar" @click="back()">
						<view class="back">
							<image class='back' :src="getImageUrl('ic_arrow_left_white_title.png')" mode="widthFix" ></image>
						</view>
						<view class="title">{{user.nick || '小秘书'}}</view>
					</view>
				</view>
				
				<view class="info-container">
					<view class="report-container">
						<view class="tip">禁止所有违法涉黄行为，借平台进行违法活动将被冻结账号</view>
						<view class="report" @click="onReport">举报</view>
					</view>
					<view class="info" v-if="user.nick">
						<view class="avatar-container">
							<image class="avatar" :src="user.headPicUrl" mode="aspectFill"></image>
							<view class='nick'>{{user.nick}}</view>
							<view class='btn' @click="toUserInfo">查看资料</view>
						</view>
						<view class="age-sign-container">
							<image :src="getImageUrl('chat_info_age.png')" style="width: 25rpx;" mode='widthFix'></image>
							<view class="text">{{user.info}}</view>
						</view>
						<view class="age-sign-container" >
							<image :src="getImageUrl('chat_info_sign.png')" style="width: 25rpx;" mode='widthFix'></image>
							<view class="text">{{user.sign || '这个家伙很懒，什么都没留下~'}}</view>
						</view>
						<view class="photo-container" v-if='user.introPicIdUrl'>
							<image :src="getImageUrl('chat_info_photo.png')" style="width: 25rpx;" mode='widthFix'></image>
							<view style="margin-left: 10rpx;">
								<image class="photo" v-for="(item, index) in user.introPicIdUrl" :key="index" :src="item" @click="onPerviewImage(index)"></image>
							</view>
						</view>
					</view>
				</view>
				
				<image class="image-bg" :src="user.headPicUrl" mode="aspectFill"></image>
				
				
				<MessageList :class="['TUI-chat-message-list', !isPC && 'TUI-chat-h5-message-list']" style="flex: 1;"
					:isGroup="isGroup" :groupID="groupID" @handleEditor="handleEditor">
				</MessageList>
				<!-- 兼容 uni 打包支付宝小程序 v-show 无效问题 -->
				<MessageInputToolbar v-if="isToolbarShow"
					:class="['TUI-chat-message-input-toolbar', !isPC && 'TUI-chat-h5-message-input-toolbar']"
					@insertEmoji="insertEmoji"></MessageInputToolbar>
				<MessageInput :class="[
            'TUI-chat-message-input',
            !isPC && 'TUI-chat-h5-message-input',
            isUniFrameWork && 'TUI-chat-uni-message-input',
            isWeChat && 'TUI-chat-wx-message-input',
          ]" ref="messageInputRef" :isMuted="false" :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')"
					:placeholder="TUITranslateService.t('请输入消息')" @handleToolbarListShow="handleToolbarListShow" v-if="user.nick">
				</MessageInput>
			</div>
			<!-- 群组管理 -->
			<div class="group-profile" v-if="isUniFrameWork && isGroup && groupManageExt" @click="handleGroup">
				{{ groupManageExt.text }}
				<!-- 更多 -->
			</div>
		</div>
		
		<uni-popup ref="vipPopup"  type="bottom" :mask-click="false">
			<view class="popup-vip">
				<image class="avatar" :src="user.headPicUrl"></image>
				<view class="title">解锁聊天</view>
				<view class="btn" @click="toVip">开通会员获得特权</view>
			</view>
		</uni-popup>
	</div>
</template>
<script lang="ts" setup>
	import TUIChatEngine, {
		TUITranslateService,
		TUIConversationService,
		TUIStore,
		StoreName,
		IMessageModel,
		IConversationModel,
	} from "@tencentcloud/chat-uikit-engine";
	import TUICore, { TUIConstants, ExtensionInfo } from "@tencentcloud/tui-core";
	import { ref, onUnmounted } from "../../adapter-vue";
	import ChatHeader from "./chat-header/index.vue";
	import MessageList from "./message-list/index.vue";
	import MessageInput from "./message-input/index.vue";
	import Forward from "./forward/index.vue";
	import MessageInputToolbar from "./message-input-toolbar/index.vue";
	import { isPC, isWeChat, isUniFrameWork } from "../../utils/env";
	import TUIChatConfig from "./config";
	import { onLoad } from "@dcloudio/uni-app";
	// import common from '@/common/common.js'

	const emits = defineEmits(["closeChat"]);
	const isToolbarShow = ref<boolean>(!isUniFrameWork);
	const messageInputRef = ref();
	const currentConversationID = ref();
	// 是否显示群组管理
	const isGroup = ref(false);
	const groupID = ref("");
	const groupManageExt = ref<ExtensionInfo>(undefined);
	const vipPopup = ref()
	
	onLoad((options) => {
	  requestUser()
	  uni.$on('openVip', ()=>{
		  vipPopup?.value.open()
	  })
	});
	
	const requestUser = () => {
		uni.$http.get('/api/user/getUserInfoByTxCode?txCode='+getApp().globalData.chatTxCode)
			.then(res=>{
				user.value = res.data;
				let info = res.data.age + '岁'
				if(res.data.heightStr){
					info += ' . ' + res.data.heightStr
				}
				if(res.data.weightStr){
					info += ' . ' + res.data.weightStr
				}
				if(res.data.areaStr){
					info += ' . ' + res.data.areaStr
				}
				user.value.info = info;
			})
	}
	
	const back = ()=>{
		uni.navigateBack()
	}
	
	TUIStore.watch(StoreName.CONV, {
		currentConversation: (conversation : IConversationModel) => {
			if (currentConversationID.value === conversation?.conversationID) {
				return;
			}
			// TUIChat 每次切换会话，需要初始化 chatType;
			TUIChatConfig.setChatType(conversation?.type);
			// 由 TUICustomerServicePlugin 插件判断如果当前会话是客服会话，则设置 chatType 并激活会话。
			TUICore.callService({
				serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
				method: TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
				params: { conversationID: conversation?.conversationID },
			});
			currentConversationID.value = conversation?.conversationID;
			isGroup.value = conversation?.type === TUIChatEngine.TYPES.CONV_GROUP;
			if (isUniFrameWork && isGroup.value && groupID.value !== conversation?.groupProfile?.groupID) {
				const extList = TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID, {
					filterManageGroup: !isGroup.value,
				});
				groupManageExt.value = extList[0];
			}
			if (isUniFrameWork && !isGroup.value) {
				groupManageExt.value = [];
			}
			groupID.value = conversation?.groupProfile?.groupID;
		},
	});

	onUnmounted(() => {
		reset();
	});

	// 清空当前 conversationID
	const reset = () => {
		TUIConversationService.switchConversation();
	};

	const closeChat = (conversationID : string) => {
		emits("closeChat", conversationID);
		reset();
	};

	const insertEmoji = (emojiObj : object) => {
		messageInputRef?.value?.insertEmoji(emojiObj);
	};

	const handleToolbarListShow = (show ?: boolean) => {
		if (isUniFrameWork) {
			isToolbarShow.value = (show === undefined) ? !isToolbarShow.value : show;
		} else {
			isToolbarShow.value = true;
		}
	};

	const handleEditor = (message : IMessageModel, type : string) => {
		if (!message || !type) return;
		switch (type) {
			case "reference":
				// todo
				break;
			case "reply":
				// todo
				break;
			case "reedit":
				if (message?.payload?.text) {
					messageInputRef?.value?.reEdit(message?.payload?.text);
				}
				break;
			default:
				break;
		}
	};

	const handleGroup = () => {
		groupManageExt.value.listener.onClicked({ groupID: groupID.value });
	};


	//以下自己添加
	const user = ref({})
	const onReport = () => {
		uni.navigateTo({
			url:'/main/report/report?userId='+user.value.id,
		})
	}
	const toVip = () => {
		uni.navigateTo({
			url:'/main/mine/vip/vip',
			fail: (error) => {
				uni.showToast({
					title: JSON.stringify(error),
					icon:'none'
				})
			}
		})
	}
	const toUserInfo = () => {
		uni.navigateTo({
			url:'/main/user/info/info?txCode='+user.value.txCode,
		})
	}
	const onPerviewImage = (index) => {
		uni.previewImage({
			urls: user.value.introPicIdUrl,
			current: index,
		});
	}
	
</script>
<style scoped lang="scss" src="./style/index.scss">
	
</style>